# from importlib import import_module
#
# from numpy import record
from Ui_mainwindow import Ui_MainWindow
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QFileDialog, QTreeView, QStyleFactory
from PyQt5.QtCore import QTimer, QCoreApplication
from PyQt5.QtGui import QPixmap
from PyQt5.QtGui import QStandardItemModel, QStandardItem
import cv2
import qimage2ndarray
import time
from Sever import ServerFunction


class CamShow(QMainWindow, Ui_MainWindow):
    def __init__(self, parent=None):
        super(CamShow, self).__init__(parent)
        self.setupUi(self)
        self.PrepWidgets()
        self.PrepParameters()
        self.CallBackFunction()
        self.noproblem = []
        self.problematic = []
        self.TreeViewer()

        self.Timer = QTimer()
        self.Timer.timeout.connect(self.TimerOutFun)

    # 对有问题的结果进行数据元素转换
    def proAppend(self):  # 返回的item是元组
        results = ServerFunction.show()
        for one_result in results:
            if (one_result[1] & one_result[2] & one_result[3] & one_result[4] & one_result[5]) == 0:
                self.noproblem.append(one_result)
            else:
                self.problematic.append(one_result)

    def SetFilePath(self):
        dirname = QFileDialog.getOpenFileName(self, "浏览", '.')
        if dirname:
            # self.FilePathLE.setText(dirname)
            filepath = dirname[0]
            self.Image = cv2.imread(filepath)
            self.DisImg()
            print(filepath)

    def CallBackFunction(self):
        self.start.clicked.connect(self.startCamera)
        self.FilePathBt.clicked.connect(self.SetFilePath)

    def TreeViewer(self):
        # problemtaic 是由{错误代码，编号}构成的元素单元 组成的list
        model = QStandardItemModel(self.treeView)
        model.setHorizontalHeaderLabels(["统计信息"])

        itemProject1 = QStandardItem("未发现问题")
        model.appendRow(itemProject1)
        Qitems = []
        for item in self.problematic:
            QItem = QStandardItem(item[0])
            Qitems.append(QItem)
            itemProject1.appendRows(Qitems)

        itemProject2 = QStandardItem("存在问题")
        model.appendRow(itemProject2)

        itemchild = []
        itemchild.append(QStandardItem("主板问题"))
        itemchild.append(QStandardItem("镙丝缺漏"))
        itemchild.append(QStandardItem("镙丝松动"))
        itemchild.append(QStandardItem("风扇未接"))
        itemchild.append(QStandardItem("风扇划伤"))
        itemProject2.appendRows(itemchild)
        for item in self.problematic:
            if (item[1]):
                itemchild[0].appendRow(QStandardItem(item[0]))
            elif (item[2]):
                itemchild[1].appendRow(QStandardItem(item[0]))
            elif (item[3]):
                itemchild[2].appendRow(QStandardItem(item[0]))
            elif (item[4]):
                itemchild[3].appendRow(QStandardItem(item[0]))
            elif item[5]:
                itemchild[4].appendRow(QStandardItem(item[0]))
        treeview = QTreeView(self.treeView)
        treeview.setModel(model)
        treeview.setStyle(QStyleFactory.create('windows'))
        treeview.expandAll()

        self.treeView.model = model
        self.treeView = treeview

    def PrepWidgets(self):
        self.PrepCamera()

    def PrepCamera(self):
        try:
            self.camera = cv2.VideoCapture(0)
            self.MsgTE.clear()
            self.MsgTE.setReadOnly()
            self.MsgTE.append('Oboard camera connected.')
        except Exception as e:
            self.MsgTE.clear()
            self.MsgTE.append(str(e))

    def PrepParameters(self):
        self.R = 1
        self.G = 1
        self.B = 1
        self.Image_num = 0
        self.recodePath = "img/"
        self.MsgTE.clear()

        self.SetContrast()
        self.SetGain()
        self.SetExposure()
        self.SetBrightness()

    # 曝光度
    def SetExposure(self):
        try:
            exposure_time_toset = 0
            self.camera.set(15, exposure_time_toset)
            self.MsgTE.append('The exposure time is set to ' + str(self.camera.get(15)))
        except Exception as e:
            self.MsgTE.append(str(e))

    # 增益
    def SetGain(self):
        gain_toset = 0
        try:
            self.camera.set(14, gain_toset)
            self.MsgTE.append('The gain is set to ' + str(self.camera.get(14)))
        except Exception as e:
            self.MsgTE.append(str(e))

    # 亮度
    def SetBrightness(self):
        brightness_toset = 0
        try:
            self.camera.set(10, brightness_toset)
            self.MsgTE.append('The brightness is set to ' + str(self.camera.get(10)))
        except Exception as e:
            self.MsgTE.append(str(e))

    # 对比度
    def SetContrast(self):
        contrast_toset = 0
        try:
            self.camera.set(11, contrast_toset)
            self.MsgTE.append('The contrast is set to ' + str(self.camera.get(11)))
        except Exception as e:
            self.MsgTE.append(str(e))

    def record(self):
        try:
            image_name = self.recodePath + 'image' + time.strftime("%Y%m%d%H%M%S", time.localtime(time.time())) + '.jpg'
            print(image_name)
            log = open('log.txt', 'a')
            log.write(image_name + '\n')

            cv2.imwrite(image_name, self.Image)
            self.MsgTE.append(image_name + ' saved.' + '\n')
        except Exception as e:
            self.MsgTE.append(str(e))
        return image_name

    def startCamera(self):
        #
        # 测试函数

        #
        imagepath = self.DisplayImg(self.Image)
        self.proAppend(imagepath)
        self.TreeViewer()
        self.MsgTE.append(imagepath + ' complished.' + '\n')

    def ColorAdjust(self, img):
        try:
            B = img[:, :, 0]
            G = img[:, :, 1]
            R = img[:, :, 2]
            B = B * self.B
            G = G * self.G
            R = R * self.R
            img1 = img
            img1[:, :, 0] = B
            img1[:, :, 1] = G
            img1[:, :, 2] = R
            return img1
        except:
            print("error")

    def TimerOutFun(self):
        success, img = self.camera.read()
        if success:
            self.Image = self.ColorAdjust(img)
            self.DisImg()
            self.Image_num += 1
            if self.Image_num % 200 == 1:
                self.test(self.record())
        else:
            print("error TimerOutFun")

    def DisImg(self):
        img = cv2.cvtColor(self.Image, cv2.COLOR_BGR2RGB)
        qimg = qimage2ndarray.array2qimage(img)
        self.DispLb.setPixmap(QPixmap(qimg))
        self.DispLb.show()

    def DisplayImg(self):
        image = self.Image
        qimg = qimage2ndarray.array2qimage(image)
        self.DispLb.setPixmap(QPixmap(qimg))
        self.DispLb.show()
        return self.record()


if __name__ == '__main__':
    app = QApplication(sys.argv)
    ui = CamShow()
    ui.show()
    sys.exit(app.exec_())
